package com.learn.concurrent.itcast.thread.safe;

public class Ticket implements Runnable{

    private int ticketNum=100;

    Object obj=new Object();

    @Override
    public void run() {
        while(true){
            /*synchronized (obj){
                if(ticketNum>0){////判断是否有票，ticketNum>0
                    //有票，让线程睡眠100毫秒
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //打印当前售出的票数字和线程名，票数减一
                    String name=Thread.currentThread().getName();
                    System.out.println("线程"+name+"销售电影票："+ticketNum--);
                }
            }*/

            sellTicket();

        }
    }

    private synchronized void sellTicket(){
        if(ticketNum>0){////判断是否有票，ticketNum>0
            //有票，让线程睡眠100毫秒
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //打印当前售出的票数字和线程名，票数减一
            String name=Thread.currentThread().getName();
            System.out.println("线程"+name+"销售电影票："+ticketNum--);
        }
    }


}
